package cn.kgc.api.util;

import cn.kgc.api.entity.CustomerUser;
import cn.kgc.api.entity.Menus;
import cn.kgc.api.entity.Users;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

public class SystemUtil{

    /**
     * 获得登录用户信息
     */
    public static Users getLoginUsers(){
        CustomerUser customerUser =
                (CustomerUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return customerUser.getSysUser();
    }

    public static List<Menus> tree(List<Menus> sysMenuList){
        //从所有菜单中找到最上级的菜单
        List<Menus> parentSysMenuList = sysMenuList.stream()
                    .filter(sysMenu -> sysMenu.getParentId() == -1)
                    .collect(Collectors.toList());

        //遍历最上级的菜单,找到父菜单的子菜单
        for (Menus sysMenu : parentSysMenuList) {
            getChildren(sysMenu,sysMenuList);
        }
        return parentSysMenuList;
    }

    private static void  getChildren(Menus parentSysMenu,List<Menus> sysMenuList){
        for (Menus sysMenu : sysMenuList) {
            //如果菜单中的父id等于父菜单的id
            if(sysMenu.getParentId().equals(parentSysMenu.getId())){
                //那么菜单是父菜单的子菜单
                parentSysMenu.getChildren().add(sysMenu);
                //找子菜单的子菜单
                getChildren(sysMenu,sysMenuList);
            }
        }
    }
}
